package com.airena.service.impl;

import com.airena.entity.dto.UserLoginDTO;
import com.airena.entity.dto.UserRegisterDTO;
import com.airena.entity.po.User;
import com.airena.exception.BaseException;
import com.airena.mapper.UserMapper;
import com.airena.service.IUserService;
import com.airena.utils.MailUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author mender
 * @since 2025-09-24
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private MailUtil mailUtil;

    public User login(UserLoginDTO userLoginDTO){
        String username = userLoginDTO.getUsername();
//        使用md5加密
        String password = DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());
        log.info("用户登录：用户名={}, 加密后密码={}", username, password);
        //1、根据用户名查询数据库中的数据
        User user=userMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new RuntimeException("账号不存在");
        }
        //密码比对
        if (!user.getPassword().equals(password)) {
            throw new RuntimeException("密码错误");
        }

        //3、返回实体对象
        return user;
    }

    /**
     * 用户注册
     * @param userRegisterDTO 用户注册信息
     * @return
     */
    @Override
    public User register(UserRegisterDTO userRegisterDTO) {
        // 检查必要字段是否为空
        if (userRegisterDTO == null) {
            throw new RuntimeException("注册信息不能为空");
        }
        
        if (!StringUtils.hasText(userRegisterDTO.getUsername())) {
            throw new RuntimeException("用户名不能为空");
        }
        
        if (!StringUtils.hasText(userRegisterDTO.getPassword())) {
            throw new RuntimeException("密码不能为空");
        }
        
        if (!StringUtils.hasText(userRegisterDTO.getConfirmPassword())) {
            throw new RuntimeException("确认密码不能为空");
        }
        
        if (!StringUtils.hasText(userRegisterDTO.getMail())) {
            throw new RuntimeException("邮箱不能为空");
        }
        
        if (!StringUtils.hasText(userRegisterDTO.getVerificationCode())) {
            throw new RuntimeException("验证码不能为空");
        }
        
        // 验证邮箱验证码
        if (!verifyMailCode(userRegisterDTO.getMail(), userRegisterDTO.getVerificationCode())) {
            throw new RuntimeException("验证码错误或已过期");
        }
        
        // 检查两次输入的密码是否一致
        if (!userRegisterDTO.getPassword().equals(userRegisterDTO.getConfirmPassword())) {
            throw new RuntimeException("两次输入的密码不一致");
        }
        
        // 检查用户名是否已存在
        User existingUser = userMapper.getByUsername(userRegisterDTO.getUsername());
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查邮箱是否已被注册
        LambdaQueryWrapper<User> eq = new QueryWrapper<User>().lambda()
                .eq(User::getMail, userRegisterDTO.getMail());
        User userMail = this.getOne(eq);
        if(userMail != null)
            throw new BaseException("邮箱已被注册");

        // 创建新用户
        User newUser = new User();
        newUser.setUsername(userRegisterDTO.getUsername());
        String password = DigestUtils.md5DigestAsHex(userRegisterDTO.getPassword().getBytes());
        newUser.setPassword(password);
        // 处理可能为null的字段
        newUser.setFullName(userRegisterDTO.getFullName() != null ? userRegisterDTO.getFullName() : "");
        newUser.setMail(userRegisterDTO.getMail() != null ? userRegisterDTO.getMail() : "");
        newUser.setStatus(1); // 默认为普通用户
        newUser.setCreatedTime(LocalDateTime.now());
        newUser.setUpdatedTime(LocalDateTime.now());
        
        // 保存用户到数据库
        this.save(newUser);
        
        // 返回保存后的用户对象（包含生成的ID）
        return newUser;
    }
    
    @Override
    public boolean verifyMailCode(String mail, String code) {
        return mailUtil.verifyCode(mail, code);
    }
}